<?php
function template_if($str) {
	if ($str == 'else')
		return '<?php else :?>';
	if ($str == 'endif')
		return '<?php endif; ?>';
	if (strpos ( $str, 'elseif(' ) === 0)
		return '<?php ' . $str . ': ?>';
	if ($str == '/')
		return '<?php endif; ?>';
	return '<?php if(' . $str . ') : ?>';
}
function template_else($str) {
	return '<?php else :?>';
}
function template_elseif($str) {
	return '<?php elseif(' . $str . '): ?>';
}

/**
   *图片地址的转换
   *@date 2011-9-26
   *@time 上午06:21:31
   */
function picurl($url,$str='pw') {
	//图片地址的转换
	if($url){
		return str_replace('/p/','/'.$str.'/',$url);
	}	
}//end picurl

function fieldoption($fields, $value = null, $space = '') {
	$options = explode ( "\n", $fields ['setup'] ['options'] );
	foreach ( $options as $r ) {
		$v = explode ( "|", $r );
		$k = trim ( $v [1] );
		$optionsarr [$k] = $v [0];
	}
	if (isset ( $value )) {
		if (strpos ( $value, ',' )) {
			$value = explode ( ",", $value );
			$data = array ();
			foreach ( ( array ) $value as $val ) {
				$data [] = $optionsarr [$val];
			}
			if ($space != '') {
				return implode ( stripcslashes ( $space ), $data );
			} else {
				return $data;
			}
		} else {
			return $optionsarr [$value];
		}
	} else {
		return $optionsarr;
	}
}

function get_arrparentid($pid, $array = array(), $arrparentid = '') {
	if (! is_array ( $array ) || ! isset ( $array [$pid] ))
		return $pid;
	$parentid = $array [$pid] ['parentid'];
	$arrparentid = $arrparentid ? $parentid . ',' . $arrparentid : $parentid;
	if ($parentid) {
		$arrparentid = get_arrparentid ( $parentid, $array, $arrparentid );
	} else {
		$data = array ();
		$data ['bid'] = $pid;
		$data ['arrparentid'] = $arrparentid;
	}
	return $arrparentid;
}

function getform($form, $info, $value = '') {
	return $form->$info ['type'] ( $info, $value );
}

function getvalidate($info) {
	$validate_data = array ();
	if ($info ['minlength'])
		$validate_data ['minlength'] = ' minlength:' . $info ['minlength'];
	if ($info ['maxlength'])
		$validate_data ['maxlength'] = ' maxlength:' . $info ['maxlength'];
	if ($info ['required'])
		$validate_data ['required'] = ' required:true';
	if ($info ['pattern'])
		$validate_data ['pattern'] = ' ' . $info ['pattern'] . ':true';
	if ($info ['errormsg'])
		$errormsg = ' title="' . $info ['errormsg'] . '"';
	$validate = implode ( ',', $validate_data );
	$validate = $validate ? 'validate="' . $validate . '" ' : '';
	$parseStr = $validate . $errormsg;
	return $parseStr;
}

function sendmail($tomail, $subject, $body, $config = '') {
	
	if (! $config)
		$config = F ( 'Config' );
	
	import ( "@.ORG.PHPMailer" );
	$mail = new PHPMailer ();
	
	if ($config ['mail_type'] == 1) {
		$mail->IsSMTP ();
	} elseif ($config ['mail_type'] == 2) {
		$mail->IsMail ();
	} else {
		if ($config ['sendmailpath']) {
			$mail->Sendmail = $config ['mail_sendmail'];
		} else {
			$mail->Sendmail = ini_get ( 'sendmail_path' );
		}
		$mail->IsSendmail ();
	}
	if ($config ['mail_auth']) {
		$mail->SMTPAuth = true; // 开启SMTP认证
	} else {
		$mail->SMTPAuth = false; // 开启SMTP认证
	}
	
	$mail->PluginDir = LIB_PATH . "ORG/";
	$mail->CharSet = 'utf-8';
	$mail->SMTPDebug = false; // 改为2可以开启调试
	$mail->Host = $config ['mail_server']; // GMAIL的SMTP
	//$mail->SMTPSecure = "ssl"; // 设置连接服务器前缀
	//$mail->Encoding = "base64";
	$mail->Port = $config ['mail_port']; // GMAIL的SMTP端口号
	$mail->Username = $config ['mail_user']; // GMAIL用户名,必须以@gmail结尾
	$mail->Password = $config ['mail_password']; // GMAIL密码
	//$mail->From ="yourphp@163.com";
	//$mail->FromName = "yourphp企业建站系统";
	$mail->SetFrom ( $config ['mail_from'], $config ['site_name'] ); //发送者邮箱
	$mail->AddAddress ( $tomail ); //可同时发多个
	//$mail->AddReplyTo('147613338@qq.com', 'yourphp'); //回复到这个邮箱
	//$mail->WordWrap = 50; // 设定 word wrap
	//$mail->AddAttachment("/var/tmp/file.tar.gz"); // 附件1
	//$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // 附件2
	$mail->IsHTML ( true ); // 以HTML发送
	$mail->Subject = $subject;
	$mail->Body = $body;
	//$mail->AltBody = "This is the body when user views in plain text format";		//纯文字时的Body
	if (! $mail->Send ()) {
		return false;
	} else {
		return true;
	}

}

function delattach($map = '') {
	$model = M ( 'Attachment' );
	$att = $model->field ( 'aid,filepath' )->where ( $map )->select ();
	$aids = array ();
	foreach ( ( array ) $att as $key => $r ) {
		$aids [] = $r ['aid'];
		@unlink ( __ROOT__ . $r ['filepath'] );
	}
	$r = $model->delete ( implode ( ',', $aids ) );
	return false !== $r ? true : false;
}

function template_file($module = '') {
	$sysConfig = F ( 'sys.config' );
	$tempfiles1 = dir_list ( TMPL_PATH . $sysConfig ['DEFAULT_THEME'] . '/Home/', 'html' );
	$tempfiles2 = dir_list ( TMPL_PATH . $sysConfig ['DEFAULT_THEME'] . '/Biz/', 'html' );
	$tempfiles = array_merge ( $tempfiles1, $tempfiles2 );
	foreach ( $tempfiles as $key => $file ) {
		$dirname = basename ( $file );
		if ($module) {
			if (strstr ( $dirname, $module . '_' )) {
				$arr [$key] ['value'] = substr ( $dirname, 0, strrpos ( $dirname, '.' ) );
				$arr [$key] ['filename'] = $dirname;
				$arr [$key] ['filepath'] = $file;
			}
		} else {
			$arr [$key] ['value'] = substr ( $dirname, 0, strrpos ( $dirname, '.' ) );
			$arr [$key] ['filename'] = $dirname;
			$arr [$key] ['filepath'] = $file;
		}
	}
	return $arr;
}

function fileext($filename) {
	return strtolower ( trim ( substr ( strrchr ( $filename, '.' ), 1, 10 ) ) );
}

function dir_path($path) {
	$path = str_replace ( '\\', '/', $path );
	if (substr ( $path, - 1 ) != '/')
		$path = $path . '/';
	return $path;
}

function dir_create($path, $mode = 0777) {
	if (is_dir ( $path ))
		return TRUE;
	$ftp_enable = 0;
	$path = dir_path ( $path );
	$temp = explode ( '/', $path );
	$cur_dir = '';
	$max = count ( $temp ) - 1;
	for($i = 0; $i < $max; $i ++) {
		$cur_dir .= $temp [$i] . '/';
		if (@is_dir ( $cur_dir ))
			continue;
		@mkdir ( $cur_dir, 0777, true );
		@chmod ( $cur_dir, 0777 );
	}
	return is_dir ( $path );
}

function dir_copy($fromdir, $todir) {
	$fromdir = dir_path ( $fromdir );
	$todir = dir_path ( $todir );
	if (! is_dir ( $fromdir ))
		return FALSE;
	if (! is_dir ( $todir ))
		dir_create ( $todir );
	$list = glob ( $fromdir . '*' );
	if (! empty ( $list )) {
		foreach ( $list as $v ) {
			$path = $todir . basename ( $v );
			if (is_dir ( $v )) {
				dir_copy ( $v, $path );
			} else {
				copy ( $v, $path );
				@chmod ( $path, 0777 );
			}
		}
	}
	return TRUE;
}

function dir_list($path, $exts = '', $list = array()) {
	$path = dir_path ( $path );
	$files = glob ( $path . '*' );
	foreach ( $files as $v ) {
		$fileext = fileext ( $v );
		if (! $exts || preg_match ( "/\.($exts)/i", $v )) {
			$list [] = $v;
			if (is_dir ( $v )) {
				$list = dir_list ( $v, $exts, $list );
			}
		}
	}
	return $list;
}

function dir_tree($dir, $parentid = 0, $dirs = array()) {
	if ($parentid == 0)
		$id = 0;
	$list = glob ( $dir . '*' );
	foreach ( $list as $v ) {
		if (is_dir ( $v )) {
			$id ++;
			$dirs [$id] = array ('id' => $id, 'parentid' => $parentid, 'name' => basename ( $v ), 'dir' => $v . '/' );
			$dirs = dir_tree ( $v . '/', $id, $dirs );
		}
	}
	return $dirs;
}

function dir_delete($dir) {
	$dir = dir_path ( $dir );
	if (! is_dir ( $dir ))
		return FALSE;
	$list = glob ( $dir . '*' );
	foreach ( $list as $v ) {
		is_dir ( $v ) ? dir_delete ( $v ) : @unlink ( $v );
	}
	return @rmdir ( $dir );
}

function toDate($time, $format = 'Y-m-d H:i:s') {
	if (empty ( $time )) {
		return '';
	}
	$format = str_replace ( '#', ':', $format );
	return date ( $format, $time );
}
function savecache($name = '', $id = '') {
	
	if ($name == 'Field') {
		if ($id) {
			$Model = M ( $name );
			$list = $Model->order ( 'listorder' )->where ( 'moduleid=' . $id )->select ();
			$pkid = 'field';
			$data = array ();
			foreach ( $list as $key => $val ) {
				$data [$val [$pkid]] = $val;
			}
			$name = $id . '_' . $name;
			F ( $name, $data );
		} else {
			$module = F ( 'Module' );
			foreach ( $module as $key => $val ) {
				savecache ( $name, $key );
			}
		}
	} elseif ($name == 'Config') {
		
		$Model = M ( $name );
		$list = $Model->select ();
		$data = $sysdata = array ();
		foreach ( $list as $key => $r ) {
			if ($r ['groupid'] == 6) {
				$sysdata [$r ['varname']] = $r ['value'];
			} else {
				$data [$r ['varname']] = $r ['value'];
			}
		}
		F ( 'Config', $data );
		F ( 'sys.config', $sysdata );
	} elseif ($name == 'Module') {
		$Model = M ( $name );
		$list = $Model->order ( 'listorder' )->select ();
		$pkid = $Model->getPk ();
		$data = array ();
		foreach ( $list as $key => $val ) {
			$data [$val [$pkid]] = $val;
			$smalldata [$val ['name']] = $val [$pkid];
		}
		F ( $name, $data );
		F ( 'Mod', $smalldata );
	
		//savecache
	

	} elseif ($name == 'Category') {
		$Model = M ( $name );
		$list = $Model->order ( 'listorder' )->select ();
		$pkid = $Model->getPk ();
		$data = array ();
		foreach ( $list as $key => $val ) {
			$data [$val [$pkid]] = $val;
			$smalldata [$val ['catdir']] = $val [$pkid];
		}
		F ( $name, $data );
		F ( 'Cat', $smalldata );
	} elseif ($name == 'Dbsource') {
		$Model = M ( $name );
		$list = $Model->select ();
		$data = array ();
		foreach ( $list as $key => $val ) {
			$data [$val ['name']] = $val;
		}
		F ( $name, $data );
	} else {
		$Model = M ( $name );
		$list = $Model->order ( 'listorder' )->select ();
		$pkid = $Model->getPk ();
		$data = array ();
		foreach ( $list as $key => $val ) {
			$data [$val [$pkid]] = $val;
		}
		F ( $name, $data );
		if ($name == 'Urlrule') {
			$config = F ( 'sys.config' );
			if ($config ['URL_URLRULE'])
				routes_cache ( $config ['URL_URLRULE'] );
		}
	}
	return true;
}

function checkfield($fields, $_POST) {
	foreach ( $_POST as $key => $val ) {
		$setup = $fields [$key] ['setup'];
		
		if (! empty ( $fields [$key] ['required'] ) && empty ( $_POST [$key] ))
			return '';
		
		//$setup=string2array($fields[$key]['setup']);
		if ($setup ['multiple'] || $setup ['inputtype'] == 'checkbox' || $fields [$key] ['type'] == 'checkbox') {
			$_POST [$key] = implode ( ',', $_POST [$key] );
		} elseif ($fields [$key] ['type'] == 'datetime') {
			$_POST [$key] = strtotime ( $_POST [$key] );
		} elseif ($fields [$key] ['type'] == 'textarea') {
			$_POST [$key] = addslashes ( $_POST [$key] );
		} elseif ($fields [$key] ['type'] == 'images' || $fields [$key] ['type'] == 'files') {
			$name = $key . '_name';
			$arrdata = array ();
			foreach ( $_POST [$key] as $k => $res ) {
				$arrdata [] = $_POST [$key] [$k] . '|' . $_POST [$name] [$k];
			}
			$_POST [$key] = implode ( ':::', $arrdata );
		} elseif ($fields [$key] ['type'] == 'editor') {
			//自动提取摘要
			if (isset ( $_POST ['add_description'] ) && $_POST ['description'] == '' && isset ( $_POST ['content'] )) {
				$content = stripslashes ( $_POST ['content'] );
				$description_length = intval ( $_POST ['description_length'] );
				$_POST ['description'] = str_cut ( str_replace ( array ("\r\n", "\t", '[page]', '[/page]', '&ldquo;', '&rdquo;' ), '', strip_tags ( $content ) ), $description_length );
				$_POST ['description'] = addslashes ( $_POST ['description'] );
			}
			//自动提取缩略图
			if (isset ( $_POST ['auto_thumb'] ) && $_POST ['thumb'] == '' && isset ( $_POST ['content'] )) {
				$content = $content ? $content : stripslashes ( $_POST ['content'] );
				$auto_thumb_no = intval ( $_POST ['auto_thumb_no'] ) * 3;
				if (preg_match_all ( "/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches )) {
					$_POST ['thumb'] = $matches [$auto_thumb_no] [0];
				}
			}
		}
	}
	return $_POST;
}

function string2array($info) {
	if ($info == '')
		return array ();
	$info = stripcslashes ( $info );
	eval ( "\$r = $info;" );
	return $r;
}

function array2string($info) {
	if ($info == '')
		return '';
	if (! is_array ( $info ))
		$string = stripslashes ( $info );
	foreach ( $info as $key => $val )
		$string [$key] = stripslashes ( $val );
	return addslashes ( var_export ( $string, TRUE ) );
}

/**
	 +----------------------------------------------------------
 * 产生随机字串，可用来自动生成密码
 * 默认长度6位 字母和数字混合 支持中文
	 +----------------------------------------------------------
 * @param string $len 长度
 * @param string $type 字串类型
 * 0 字母 1 数字 其它 混合
 * @param string $addChars 额外字符
	 +----------------------------------------------------------
 * @return string
	 +----------------------------------------------------------
 */
function rand_string($len = 6, $type = '', $addChars = '') {
	$str = '';
	switch ($type) {
		case 0 :
			$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars;
			break;
		case 1 :
			$chars = str_repeat ( '0123456789', 3 );
			break;
		case 2 :
			$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars;
			break;
		case 3 :
			$chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars;
			break;
		default :
			// 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数
			$chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars;
			break;
	}
	if ($len > 10) { //位数过长重复字符串一定次数
		$chars = $type == 1 ? str_repeat ( $chars, $len ) : str_repeat ( $chars, 5 );
	}
	if ($type != 4) {
		$chars = str_shuffle ( $chars );
		$str = substr ( $chars, 0, $len );
	} else {
		// 中文随机字
		for($i = 0; $i < $len; $i ++) {
			$str .= msubstr ( $chars, floor ( mt_rand ( 0, mb_strlen ( $chars, 'utf-8' ) - 1 ) ), 1 );
		}
	}
	return $str;
}
function sysmd5($str, $key = '', $type = 'sha1') {
	$key = $key ? $key : C ( 'ADMIN_ACCESS' );
	return hash ( $type, $str . $key );
}
function pwdHash($password, $type = 'md5') {
	return hash ( $type, $password );
}

/**
 * @param string $string 原文或者密文
 * @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE
 * @param string $key 密钥
 * @param int $expiry 密文有效期, 加密时候有效， 单位 秒，0 为永久有效
 * @return string 处理后的 原文或者 经过 base64_encode 处理后的密文
 *
 * @example
 *
 * $a = authcode('abc', 'ENCODE', 'key');
 * $b = authcode($a, 'DECODE', 'key');  // $b(abc)
 *
 * $a = authcode('abc', 'ENCODE', 'key', 3600);
 * $b = authcode('abc', 'DECODE', 'key'); // 在一个小时内，$b(abc)，否则 $b 为空
 */
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	$ckey_length = 4;
	// 随机密钥长度 取值 0-32;
	// 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
	// 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
	// 当此值为 0 时，则不产生随机密钥
	

	$key = md5 ( $key ? $key : EABAX::getAppInf ( 'KEY' ) );
	$keya = md5 ( substr ( $key, 0, 16 ) );
	$keyb = md5 ( substr ( $key, 16, 16 ) );
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr ( $string, 0, $ckey_length ) : substr ( md5 ( microtime () ), - $ckey_length )) : '';
	
	$cryptkey = $keya . md5 ( $keya . $keyc );
	$key_length = strlen ( $cryptkey );
	
	$string = $operation == 'DECODE' ? base64_decode ( substr ( $string, $ckey_length ) ) : sprintf ( '%010d', $expiry ? $expiry + time () : 0 ) . substr ( md5 ( $string . $keyb ), 0, 16 ) . $string;
	$string_length = strlen ( $string );
	
	$result = '';
	$box = range ( 0, 255 );
	
	$rndkey = array ();
	for($i = 0; $i <= 255; $i ++) {
		$rndkey [$i] = ord ( $cryptkey [$i % $key_length] );
	}
	
	for($j = $i = 0; $i < 256; $i ++) {
		$j = ($j + $box [$i] + $rndkey [$i]) % 256;
		$tmp = $box [$i];
		$box [$i] = $box [$j];
		$box [$j] = $tmp;
	}
	
	for($a = $j = $i = 0; $i < $string_length; $i ++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box [$a]) % 256;
		$tmp = $box [$a];
		$box [$a] = $box [$j];
		$box [$j] = $tmp;
		$result .= chr ( ord ( $string [$i] ) ^ ($box [($box [$a] + $box [$j]) % 256]) );
	}
	
	if ($operation == 'DECODE') {
		if ((substr ( $result, 0, 10 ) == 0 || substr ( $result, 0, 10 ) - time () > 0) && substr ( $result, 10, 16 ) == substr ( md5 ( substr ( $result, 26 ) . $keyb ), 0, 16 )) {
			return substr ( $result, 26 );
		} else {
			return '';
		}
	} else {
		return $keyc . str_replace ( '=', '', base64_encode ( $result ) );
	}
}

// 获取客户端IP地址
function get_client_ip() {
	if (getenv ( "HTTP_CLIENT_IP" ) && strcasecmp ( getenv ( "HTTP_CLIENT_IP" ), "unknown" ))
		$ip = getenv ( "HTTP_CLIENT_IP" );
	else if (getenv ( "HTTP_X_FORWARDED_FOR" ) && strcasecmp ( getenv ( "HTTP_X_FORWARDED_FOR" ), "unknown" ))
		$ip = getenv ( "HTTP_X_FORWARDED_FOR" );
	else if (getenv ( "REMOTE_ADDR" ) && strcasecmp ( getenv ( "REMOTE_ADDR" ), "unknown" ))
		$ip = getenv ( "REMOTE_ADDR" );
	else if (isset ( $_SERVER ['REMOTE_ADDR'] ) && $_SERVER ['REMOTE_ADDR'] && strcasecmp ( $_SERVER ['REMOTE_ADDR'], "unknown" ))
		$ip = $_SERVER ['REMOTE_ADDR'];
	else
		$ip = "unknown";
	return ($ip);
}

//字符串截取
function str_cut($sourcestr, $cutlength, $suffix = '...') {
	$returnstr = '';
	$i = 0;
	$n = 0;
	$str_length = strlen ( $sourcestr ); //字符串的字节数
	while ( ($n < $cutlength) and ($i <= $str_length) ) {
		$temp_str = substr ( $sourcestr, $i, 1 );
		$ascnum = Ord ( $temp_str ); //得到字符串中第$i位字符的ascii码
		if ($ascnum >= 224) //如果ASCII位高与224，
{
			$returnstr = $returnstr . substr ( $sourcestr, $i, 3 ); //根据UTF-8编码规范，将3个连续的字符计为单个字符
			$i = $i + 3; //实际Byte计为3
			$n ++; //字串长度计1
		} elseif ($ascnum >= 192) //如果ASCII位高与192，
{
			$returnstr = $returnstr . substr ( $sourcestr, $i, 2 ); //根据UTF-8编码规范，将2个连续的字符计为单个字符
			$i = $i + 2; //实际Byte计为2
			$n ++; //字串长度计1
		} elseif ($ascnum >= 65 && $ascnum <= 90) //如果是大写字母，
{
			$returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
			$i = $i + 1; //实际的Byte数仍计1个
			$n ++; //但考虑整体美观，大写字母计成一个高位字符
		} else //其他情况下，包括小写字母和半角标点符号，
{
			$returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
			$i = $i + 1; //实际的Byte数计1个
			$n = $n + 0.5; //小写字母和半角标点等与半个高位字符宽...
		}
	}
	
	if ($str_length / 3 > $cutlength) {
		$returnstr = $returnstr . $suffix; //超过长度时在尾处加上省略号
	}
	return $returnstr;

}

function IP($ip = '', $file = 'UTFWry.dat') {
	import ( "@.ORG.IpLocation" );
	$iplocation = new IpLocation ( $file );
	$location = $iplocation->getlocation ( $ip );
	return $location;
}

function byte_format($input, $dec = 0) {
	$prefix_arr = array ("B", "K", "M", "G", "T" );
	$value = round ( $input, $dec );
	$i = 0;
	while ( $value > 1024 ) {
		$value /= 1024;
		$i ++;
	}
	$return_str = round ( $value, $dec ) . $prefix_arr [$i];
	return $return_str;
}

/**
 +----------------------------------------------------------
 * 代码加亮
 +----------------------------------------------------------
 * @param String  $str 要高亮显示的字符串 或者 文件名
 * @param Boolean $show 是否输出
 +----------------------------------------------------------
 * @return String
 +----------------------------------------------------------
 */
function highlight_code($str, $show = false) {
	if (file_exists ( $str )) {
		$str = file_get_contents ( $str );
	}
	$str = stripslashes ( trim ( $str ) );
	$str = str_replace ( array ('&lt;', '&gt;' ), array ('<', '>' ), $str );
	$str = str_replace ( array ('&lt;?php', '?&gt;', '\\' ), array ('phptagopen', 'phptagclose', 'backslashtmp' ), $str );
	$str = '<?php //tempstart' . "\n" . $str . '//tempend ?>'; // <?
	$str = highlight_string ( $str, TRUE );
	if (abs ( phpversion () ) < 5) {
		$str = str_replace ( array ('<font ', '</font>' ), array ('<span ', '</span>' ), $str );
		$str = preg_replace ( '#color="(.*?)"#', 'style="color: \\1"', $str );
	}
	// Remove our artificially added PHP
	$str = preg_replace ( "#\<code\>.+?//tempstart\<br />\</span\>#is", "<code>\n", $str );
	$str = preg_replace ( "#\<code\>.+?//tempstart\<br />#is", "<code>\n", $str );
	$str = preg_replace ( "#//tempend.+#is", "</span>\n</code>", $str );
	// Replace our markers back to PHP tags.
	$str = str_replace ( array ('phptagopen', 'phptagclose', 'backslashtmp' ), array ('&lt;?php', '?&gt;', '\\' ), $str ); //<?
	$line = explode ( "<br />", rtrim ( ltrim ( $str, '<code>' ), '</code>' ) );
	$result = '<div class="code"><ol>';
	foreach ( $line as $key => $val ) {
		$result .= '<li>' . $val . '</li>';
	}
	$result .= '</ol></div>';
	$result = str_replace ( "\n", "", $result );
	if ($show !== false) {
		echo ($result);
	} else {
		return $result;
	}
}

function color_txt($str) {
	if (function_exists ( 'iconv_strlen' )) {
		$len = iconv_strlen ( $str );
	} else if (function_exists ( 'mb_strlen' )) {
		$len = mb_strlen ( $str );
	}
	$colorTxt = '';
	for($i = 0; $i < $len; $i ++) {
		$colorTxt .= '<span style="color:' . rand_color () . '">' . msubstr ( $str, $i, 1, 'utf-8', '' ) . '</span>';
	}
	
	return $colorTxt;
}
function showExt($ext, $pic = true) {
	static $_extPic = array ('dir' => "folder.gif", 'doc' => 'msoffice.gif', 'rar' => 'rar.gif', 'zip' => 'zip.gif', 'txt' => 'text.gif', 'pdf' => 'pdf.gif', 'html' => 'html.gif', 'png' => 'image.gif', 'gif' => 'image.gif', 'jpg' => 'image.gif', 'php' => 'text.gif' );
	static $_extTxt = array ('dir' => '文件夹', 'jpg' => 'JPEG图象' );
	if ($pic) {
		if (array_key_exists ( strtolower ( $ext ), $_extPic )) {
			$show = "<IMG SRC='" . WEB_PUBLIC_PATH . "/Images/extension/" . $_extPic [strtolower ( $ext )] . "' BORDER='0' alt='' align='absmiddle'>";
		} else {
			$show = "<IMG SRC='" . WEB_PUBLIC_PATH . "/Images/extension/common.gif' WIDTH='16' HEIGHT='16' BORDER='0' alt='文件' align='absmiddle'>";
		}
	} else {
		if (array_key_exists ( strtolower ( $ext ), $_extTxt )) {
			$show = $_extTxt [strtolower ( $ext )];
		} else {
			$show = $ext ? $ext : '文件夹';
		}
	}
	
	return $show;
}

/**
 +----------------------------------------------------------
 * 获取登录验证码 默认为4位数字
 +----------------------------------------------------------
 * @param string $fmode 文件名
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function build_verify($length = 4, $mode = 1) {
	return rand_string ( $length, $mode );
}

function make_urlrule($url,$module,$action,$MOREREQUEST=''){
	preg_match_all ("/({([\w\$]+)})/",$url, $matches);
	$REQUEST= implode(',',$matches[0]);
	$REQUEST=str_replace(array('{$parentdir}','{$module}','{$moduleid}','{$catdir}','{$year}','{$month}','{$day}','{$catid}','{$id}','{$page}'),array('','module','moduleid','catdir','year','month','day','catid','id',C('VAR_PAGE')),$REQUEST);
	$rule=str_replace(array('{$parentdir}','{$module}','{$moduleid}','{$catdir}','{$year}','{$month}','{$day}','{$catid}','{$id}','{$page}','/'),array('(\w+)','([A-Z]{1}[a-z]+)','(\d+)','(\w+)','(\d+)','(\d+)','(\d+)','(\d+)','(\d+)','(\d+)','\/'),$url);
	$urlrule='array(\'/^'.$rule.'$/\',\''.$module.'/'.$action.'\',\''.$REQUEST.'\',\''.$MOREREQUEST.'\')';
	return str_replace('\/$','$',$urlrule);
}
function routes_cache($URL_URLRULE=''){
	$URL_URLRULE = $URL_URLRULE ? $URL_URLRULE : C('URL_URLRULE'); 
	$urlrule = is_array($URL_URLRULE) ?  $URL_URLRULE : explode(':::',$URL_URLRULE);
	$list=explode('|',$urlrule[1]);
	$show=explode('|',$urlrule[0]);
	$listurls[]= make_urlrule($list[0],'Urlrule','index');
	$listurls[]= make_urlrule($list[1],'Urlrule','index');
	$listurls[]= make_urlrule($show[0],'Urlrule','show');
	$listurls[]= make_urlrule($show[1],'Urlrule','show');
	$url = implode(",\n",$listurls); 
	file_put_contents(DATA_PATH.'Routes.php', "<?php\nreturn array(\n" . $url . "\n);\n?>");
	if(is_file(RUNTIME_PATH.'~app.php'))@unlink(RUNTIME_PATH.'~app.php');
	if(is_file(RUNTIME_PATH.'~runtime.php'))@unlink(RUNTIME_PATH.'~runtime.php');
	if(is_file(RUNTIME_PATH.'~allinone.php'))@unlink(RUNTIME_PATH.'~allinone.php');	
}

function geturl($cat,$data='',$Urlrule=''){
		//$Urlrule =F('Urlrule');
		$id=$data['id'];
 
		$URL_MODEL =C('URL_M');
		if($URL_MODEL==0){
			if($id){
				$url[] = U("Home-$cat[module]/show?id=$id");
				$url[] = U("Home-$cat[module]/show?id=".$id.'&'.C('VAR_PAGE').'={$page}');		
			}else{
				$url[] = U("Home-$cat[module]/index?id=$cat[id]");
				$url[] = U("Home-$cat[module]/index?id=$cat[id]&".C('VAR_PAGE').'={$page}');			
			}
			$urls = str_replace('g=Admin&','',$url);
			$urls = str_replace('g=Home&','',$url);		
		}else{
			if($URL_MODEL==1)$index='index.php/';
			$parentdir = $cat['parentdir'];
			$catdir = $cat['catdir'];
			$year = date('Y',$data['createtime']);
			$month = date('m',$data['createtime']);
			$day = date('d',$data['createtime']);
			$module = $cat['module'];
			$moduleid =$cat['moduleid'];
			$catid=$cat['id'];
			if($cat['ishtml'] && $cat['urlruleid'] && $Urlrule){
				$index='';
				$showurlrule = $Urlrule[$cat['urlruleid']]['showurlrule'];
				$listurlrule = $Urlrule[$cat['urlruleid']]['listurlrule'];
			}else{
				$urlrule = explode(':::',C('URL_URLRULE'));
				$showurlrule = $urlrule[0];
				$listurlrule = $urlrule[1];
			}
			if($id){
				$urls = str_replace(array('{$parentdir}','{$module}','{$moduleid}','{$catdir}','{$year}','{$month}','{$day}','{$catid}','{$id}'),array($parentdir,$module,$moduleid,$catdir,$year,$month,$day,$catid,$id),$showurlrule);
			
			}else{
				$urls = str_replace(array('{$parentdir}','{$module}','{$moduleid}','{$catdir}','{$year}','{$month}','{$day}','{$catid}','{$id}'),array($parentdir,$module,$moduleid,$catdir,$year,$month,$day,$catid,$id),$listurlrule);
			}

			$urls = explode('|',$urls);
			$urls[0]=$index.$urls[0];
			$urls[1]=$index.$urls[1];
		}
		return $urls;
}
function content_pages($num, $p, $pageurls) {
	
	$multipage = '';
	$page = 11;
	$offset = 4;
	$pages = $num;
	$from = $p - $offset;
	$to = $p + $offset;
	$more = 0;
	if ($page >= $pages) {
		$from = 2;
		$to = $pages - 1;
	} else {
		if ($from <= 1) {
			$to = $page - 1;
			$from = 2;
		} elseif ($to >= $pages) {
			$from = $pages - ($page - 2);
			$to = $pages - 1;
		}
		$more = 1;
	}
	if ($p > 0) {
		$perpage = $p == 1 ? 1 : $p - 1;
		if ($perpage == 1) {
			$multipage .= '<a class="a1" href="' . $pageurls [$perpage] [0] . '">' . L ( 'previous' ) . '</a>';
		} else {
			$multipage .= '<a class="a1" href="' . $pageurls [$perpage] [1] . '">' . L ( 'previous' ) . '</a>';
		}
		if ($p == 1) {
			$multipage .= ' <span>1</span>';
		} elseif ($p > 6 && $more) {
			$multipage .= ' <a href="' . $pageurls [1] [0] . '">1</a>..';
		} else {
			$multipage .= ' <a href="' . $pageurls [1] [0] . '">1</a>';
		}
	}
	for($i = $from; $i <= $to; $i ++) {
		if ($i != $p) {
			$multipage .= ' <a href="' . $pageurls [$i] [1] . '">' . $i . '</a>';
		} else {
			$multipage .= ' <span>' . $i . '</span>';
		}
	}
	if ($p < $pages) {
		if ($p < $pages - 5 && $more) {
			$multipage .= ' ..<a href="' . $pageurls [$pages] [1] . '">' . $pages . '</a> <a class="a1" href="' . $pageurls [$p + 1] [1] . '">' . L ( 'next' ) . '</a>';
		} else {
			$multipage .= ' <a href="' . $pageurls [$pages] [1] . '">' . $pages . '</a> <a class="a1" href="' . $pageurls [$p + 1] [1] . '">' . L ( 'next' ) . '</a>';
		}
	} elseif ($p == $pages) {
		$multipage .= ' <span>' . $pages . '</span> <a class="a1" href="' . $pageurls [$p] [1] . '">' . L ( 'next' ) . '</a>';
	}
	return $multipage;
}

function thumb($f, $tw=300, $th=300 ,$autocat=0, $nopic = 'nopic.jpg',$t=''){
	if(empty($f)) return WEB_PUBLIC_PATH.'/Images/'.$nopic;
	$pathinfo = pathinfo ( $f );
	if (empty ( $t )) {
		$t = $pathinfo ['dirname'] . '/thumb_' . $tw . '_' . $th . '_' . $pathinfo ['basename'];
		if (is_file ( $t )) {
			return $t;
		}
	}
	$temp = array (1 => 'gif', 2 => 'jpeg', 3 => 'png' );
	list ( $fw, $fh, $tmp ) = getimagesize ( $f );
	if (! $temp [$tmp]) {
		return false;
	}
	
	if ($autocat) {
		if ($fw / $tw > $fh / $th) {
			$fw = $tw * ($fh / $th);
		} else {
			$fh = $th * ($fw / $tw);
		}
	} else {
		
		$scale = min ( $tw / $fw, $th / $fh ); // 计算缩放比例
		if ($scale >= 1) {
			// 超过原图大小不再缩略
			$tw = $fw;
			$th = $fh;
		} else {
			// 缩略图尺寸
			$tw = ( int ) ($fw * $scale);
			$th = ( int ) ($fh * $scale);
		}
	
	}
	
	$tmp = $temp [$tmp];
	$infunc = "imagecreatefrom$tmp";
	$outfunc = "image$tmp";
	$fimg = $infunc ( $f );
	
	if ($tmp != 'gif' && function_exists ( 'imagecreatetruecolor' )) {
		$timg = imagecreatetruecolor ( $tw, $th );
	} else {
		$timg = imagecreate ( $tw, $th );
	}
	
	if (function_exists ( 'imagecopyresampled' ))
		imagecopyresampled ( $timg, $fimg, 0, 0, 0, 0, $tw, $th, $fw, $fh );
	else
		imagecopyresized ( $timg, $fimg, 0, 0, 0, 0, $tw, $th, $fw, $fh );
	if ($tmp == 'gif' || $tmp == 'png') {
		$background_color = imagecolorallocate ( $timg, 0, 255, 0 ); //  指派一个绿色
		imagecolortransparent ( $timg, $background_color ); //  设置为透明色，若注释掉该行则输出绿色的图
	}
	$outfunc ( $timg, $t );
	imagedestroy ( $timg );
	imagedestroy ( $fimg );
	return $t;
}

/**
 +----------------------------------------------------------
 * 把返回的数据集转换成Tree
 +----------------------------------------------------------
 * @access public
 +----------------------------------------------------------
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 +----------------------------------------------------------
 * @return array
 +----------------------------------------------------------
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0) {
	// 创建Tree
	$tree = array ();
	if (is_array ( $list )) {
		// 创建基于主键的数组引用
		$refer = array ();
		foreach ( $list as $key => $data ) {
			$refer [$data [$pk]] = & $list [$key];
		}
		foreach ( $list as $key => $data ) {
			// 判断是否存在parent
			$parentId = $data [$pid];
			if ($root == $parentId) {
				$tree [] = & $list [$key];
			} else {
				if (isset ( $refer [$parentId] )) {
					$parent = & $refer [$parentId];
					$parent [$child] [] = & $list [$key];
				}
			}
		}
	}
	return $tree;
}

function br2nl($text) {
	return preg_replace ( '/<br\\s*?\/??>/i', '', $text );
}

/**
 * 给数组的匹配项加上checked
 *
 * @param  $arr 待核对值
 * @param  $value 匹配值
 * @param	$type 输出字符
 * @return  string
 */
function arrayischk($arr, $value = '-100', $type = 'checked') {
	$re = '';
	if ($value == '-100') {
		$re = empty ( $arr ) ? '' : $type == 'checked' || $type == 'selected' ? " $type=$type" : "$type";
	} else {
		$re = ($arr == $value) ? $type == 'checked' || $type == 'selected' ? " $type=$type" : "$type" : '';
	}
	return $re;
}

/**
 * 将数组用指定字符连接
 *
 * @param  $array 数组
 * @param  $split 分隔符
 * @return  string
 */
function arr2str($array, $split = ',') {
	if (is_array ( $array )) {
		$dot = '';
		foreach ( $array as $data ) {
			$string .= $dot . $data;
			$dot = $split;
		}
		return empty ( $string ) ? '' : $string;
	} else {
		return $array;
	}
}

/**
 * 将指定数据转换成数组再对比，符合条件则返回checked
 *
 * @param  $sring 输入字符
 * @param  $param 条件
 * @param  $split 分隔符
 * @return  string
 */
function string2checked($sring, $param, $split = ',', $type = 'checked') {
	$splitParam = explode ( $split, $param );
	if (in_array ( $sring, $splitParam ))
		$result = $type == 'checked' || $type == 'selected' ? " $type=$type" : "$type";
	return $result;
}

/**
 *
 * 下拉框，单选按钮 自动选择
 * @param  $string 输入字符
 * @param  $param 条件
 * @param  $type 类型  selected checked
 * @return   string
 */
function selected($string, $param = 1, $type = 'select') {
	if ($string == $param) {
		$returnString = $type == 'select' ? 'selected="selected"' : 'checked="checked"';
	}
	return $returnString;
}

/**
 *编码需要打开的网址
 *@date 2010-9-8
 *@time 下午06:06:25
 *@param $url 网址
 *@param $id arc表ID
 */
function jump($url, $id = 0) {
	//编码需要打开的网址
	$url = $url . '||' . $id;
	$url = myencode ( $url );
	return __APP__ . '/jump/' . $url . '.html';
} //end jump


function myencode($string) {
	$data = base64_encode ( $string );
	$data = str_replace ( array ('+', '/', '=' ), array ('-', '_', '' ), $data );
	return $data;
}

function mydecode($string) {
	$data = str_replace ( array ('-', '_' ), array ('+', '/' ), $string );
	$mod4 = strlen ( $data ) % 4;
	if ($mod4) {
		$data .= substr ( '====', $mod4 );
	}
	return base64_decode ( $data );
}

/**
 *将支付串转成网址适应格式
 *@date 2011-1-13 / @time 下午05:45:02
 */
function str_to_url($str, $str2 = '', $leng = 90) {
	//将支付串转成网址适应格式
	$str = Pinyin ( $str, 1 );
	$str = substr ( strtolower ( str_replace ( ' ', '-', str_replace ( '  ', ' ', trim ( preg_replace ( "/[^_a-zA-Z0-9-]/", " ", $str ), " -" ) ) ) ), 0, 100 );
	if ($str2 != '') {
		$str = substr ( $str, 0, $leng ) . $str2;
	} else {
		$str = substr ( $str, 0, $leng );
	}
	return $str;
} //end str_to_url


//将汉字专为拼音start
function Pinyin($_String, $_Code = 'gb2312') {
	$_DataKey = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha" . "|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|" . "cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er" . "|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui" . "|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang" . "|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang" . "|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue" . "|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne" . "|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen" . "|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang" . "|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|" . "she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|" . "tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu" . "|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you" . "|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|" . "zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo";
	
	$_DataValue = "-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990" . "|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725" . "|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263" . "|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003" . "|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697" . "|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211" . "|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922" . "|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468" . "|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664" . "|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407" . "|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959" . "|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652" . "|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369" . "|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128" . "|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914" . "|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645" . "|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149" . "|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087" . "|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658" . "|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340" . "|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888" . "|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585" . "|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847" . "|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055" . "|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780" . "|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274" . "|-10270|-10262|-10260|-10256|-10254";
	$_TDataKey = explode ( '|', $_DataKey );
	$_TDataValue = explode ( '|', $_DataValue );
	
	$_Data = (PHP_VERSION >= '5.0') ? array_combine ( $_TDataKey, $_TDataValue ) : _Array_Combine ( $_TDataKey, $_TDataValue );
	arsort ( $_Data );
	reset ( $_Data );
	
	if ($_Code != 'gb2312')
		$_String = _U2_Utf8_Gb ( $_String );
	$_Res = '';
	for($i = 0; $i < strlen ( $_String ); $i ++) {
		$_P = ord ( substr ( $_String, $i, 1 ) );
		
		if ($_P > 160) {
			$_Q = ord ( substr ( $_String, ++ $i, 1 ) );
			$_P = $_P * 256 + $_Q - 65536;
		}
		$_Res .= _Pinyin ( $_P, $_Data );
	}
	return $_Res; //preg_replace ( "/[^a-zA-Z0-9]*/", '', $_Res );
}

function _Pinyin($_Num, $_Data) {
	if ($_Num > 0 && $_Num < 160)
		return chr ( $_Num );
	elseif ($_Num < - 20319 || $_Num > - 10247)
		return '';
	else {
		foreach ( $_Data as $k => $v ) {
			if ($v <= $_Num)
				break;
		}
		return $k . '-';
	}
}

function _U2_Utf8_Gb($_C) {
	/*$_String = '';
	if ($_C < 0x80)
		$_String .= $_C;
	elseif ($_C < 0x800) {
		$_String .= chr ( 0xC0 | $_C >> 6 );
		$_String .= chr ( 0x80 | $_C & 0x3F );
	} elseif ($_C < 0x10000) {
		$_String .= chr ( 0xE0 | $_C >> 12 );
		$_String .= chr ( 0x80 | $_C >> 6 & 0x3F );
		$_String .= chr ( 0x80 | $_C & 0x3F );
	} elseif ($_C < 0x200000) {
		$_String .= chr ( 0xF0 | $_C >> 18 );
		$_String .= chr ( 0x80 | $_C >> 12 & 0x3F );
		$_String .= chr ( 0x80 | $_C >> 6 & 0x3F );
		$_String .= chr ( 0x80 | $_C & 0x3F );
	}*/
	return iconv ( 'UTF-8', 'GB2312//IGNORE', $_C );
}

function _Array_Combine($_Arr1, $_Arr2) {
	for($i = 0; $i < count ( $_Arr1 ); $i ++)
		$_Res [$_Arr1 [$i]] = $_Arr2 [$i];
	return $_Res;
}

/**
 *修正图片地址
 *@date 2011-7-22
 *@time 上午11:27:29
 */
function img_path($url = '') {
	//修正图片地址
	$arr = explode ( '/', $url );
	if ($arr ['0'] == '.') {
		$url = str_replace ( "./", '/', $url );
	}
	return $url;
} //end img_path
//将汉字专为拼音end


/**
     +----------------------------------------------------------
 * 根据字符串生成唯一码
 * 传入字符串 返回唯一码
 * @date 2011-3-5 - @time 下午06:19:12
     +----------------------------------------------------------
 * @static
 * @access public
     +----------------------------------------------------------
 * @param string $input
     +----------------------------------------------------------
 * @return void
     +----------------------------------------------------------
 */
function shorturl($input) {
	$base32 = array ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5' );
	
	$hex = md5 ( $input );
	//echo "md5:".$hex.'<br>';
	$hexLen = strlen ( $hex );
	$subHexLen = $hexLen / 8;
	$output = array ();
	
	for($i = 0; $i < $subHexLen; $i ++) {
		$subHex = substr ( $hex, $i * 8, 8 );
		//echo $i."substr: ".$subHex.'<br>';
		$int = 0x3FFFFFFF & (1 * ('0x' . $subHex));
		//echo $i."0x3FFFFFFF: ".$int.'<br>';
		$out = '';
		
		for($j = 0; $j < 6; $j ++) {
			$val = 0x0000001F & $int;
			//echo $i.$j."0x0000001F: ".$val.'<br>';
			$out .= $base32 [$val];
			
			$int = $int >> 5;
		}
		
		$output [] = $out;
	}
	return $output ['0'];
}
?>